﻿
using System.Windows;
using System.Collections.Generic;
using System.Windows.Controls;
using Microsoft.Phone.Tasks;
using System;
using System.Windows.Navigation;
using CDFWPUG.Model;
using System.Net;
using Microsoft.Phone.Net.NetworkInformation;
using System.Linq;
using System.Windows.Threading;
using GalaSoft.MvvmLight;
using WP7Contrib.Communications;
using WP7Contrib.Collections;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;

namespace CDFWPUG.ViewModel
{
    /// <summary>
    /// This class contains properties that a View can data bind to.
    /// <para>
    /// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel.
    /// </para>
    /// <para>
    /// You can also use Blend to data bind with the tool's support.
    /// </para>
    /// <para>
    /// See http://www.galasoft.ch/mvvm/getstarted
    /// </para>
    /// </summary>
    public class panMainViewModel : ViewModelBase
    {


        ResourceClientFactory factory;

        /// <summary>
        /// Initializes a new instance of the panMainViewModel class.
        /// </summary>
        public panMainViewModel()
        {
            if (IsInDesignMode)
            {
                // Code runs in Blend --> create design time data.
                _apps = Helpers.AppHelper.Test_GetFeaturedUserApps(3);
                _UpcomingMeetings = Helpers.MeetingHelper.Test_GetUpcomingMeetings(3);
                _MainMenuItems = Helpers.MenuItemHelper.GetMainMenuItems();
                _Tweets = Helpers.TwitterHelper.Test_GetTweets();
            }
            else
            {
                _UpcomingMeetings = new ObservableCollection<Meeting>();
                _Tweets = new ObservableCollection<Tweet>();
                _apps = new ObservableCollection<UserApp>();
                _MainMenuItems = new ObservableCollection<MenuItem>();
                factory = new ResourceClientFactory();
                LoadGroupApps();
                LoadMeetings();
                LoadTweets();
                LoadMainMenuItems();
            }

            MeetingSelectionCommand = new RelayCommand<SelectionChangedEventArgs>(HandleMeetingSelectionCommand);
            GroupAppSelectionCommand = new RelayCommand<SelectionChangedEventArgs>(HandleGroupAppSelectionCommand);
            MainMenuSelectionCommand = new RelayCommand<SelectionChangedEventArgs>(HandleMainMenuSelectionCommand);
            TwitterSearchCommand = new RelayCommand(HandleTwitterSearchCommand);
            GroupAppsSearchCommand = new RelayCommand(HandleGroupAppsSearchCommand);
            ShowAllGroupAppsCommand = new RelayCommand(HandleShowAllGroupAppsCommand);
            MeetingsSearchCommand = new RelayCommand(HandleMeetingsSearchCommand);
        }

        #region Properties
        private ObservableCollection<Model.UserApp> _apps;
        public ObservableCollection<Model.UserApp> Apps
        {
            get
            {
                return _apps;
            }
            set
            {
                _apps = value;
                RaisePropertyChanged("Apps");
            }

        }

        private ObservableCollection<Model.Meeting> _UpcomingMeetings;
        public ObservableCollection<Model.Meeting> UpcomingMeetings
        {
            get
            {
                return _UpcomingMeetings;
            }
            set
            {
                _UpcomingMeetings = value;
                RaisePropertyChanged("UpcomingMeetings");
            }

        }

        private ObservableCollection<Model.MenuItem> _MainMenuItems;
        public ObservableCollection<Model.MenuItem> MainMenuItems
        {
            get
            {
                return _MainMenuItems;
            }
            set
            {
                _MainMenuItems = value;
                RaisePropertyChanged("MainMenuItems");
            }

        }

        private Model.Meeting _SelectedMeeting;
        public Model.Meeting SelectedMeeting
        {
            get { return _SelectedMeeting; }
            set
            {
                if (_SelectedMeeting != value)
                {
                    _SelectedMeeting = value;
                    RaisePropertyChanged("SelectedMeeting");
                }
                
            }
        }

        private Model.UserApp _SelectedApp;
        public Model.UserApp SelectedApp
        {
            get { return _SelectedApp; }
            set
            {
                if (_SelectedApp != value)
                {
                    _SelectedApp = value;
                    RaisePropertyChanged("SelectedApp");
                }

            }
        }

        private ObservableCollection<Model.Tweet> _Tweets;
        public ObservableCollection<Model.Tweet> Tweets
        {
            get
            {
                return _Tweets;
            }
            set
            {
                _Tweets = value;
                RaisePropertyChanged("Tweets");
            }

        }

        private Boolean _TwitterLoading;
        public  Boolean TwitterLoading
        {
            get { return _TwitterLoading; }
            set
            {
                if (_TwitterLoading != value)
                {
                    _TwitterLoading = value;
                    RaisePropertyChanged("TwitterLoading");
                }

            }
        }

        private String _TwitterMessage;
        public String TwitterMessage
        {
            get { return _TwitterMessage; }
            set
            {
                if (_TwitterMessage != value)
                {
                    _TwitterMessage = value;
                    RaisePropertyChanged("TwitterMessage");
                }

            }
        }

        private Boolean _GroupAppsLoading;
        public Boolean GroupAppsLoading
        {
            get { return _GroupAppsLoading; }
            set
            {
                if (_GroupAppsLoading != value)
                {
                    _GroupAppsLoading = value;
                    RaisePropertyChanged("GroupAppsLoading");
                }

            }
        }

        private String _GroupAppsMessage;
        public String GroupAppsMessage
        {
            get { return _GroupAppsMessage; }
            set
            {
                if (_GroupAppsMessage != value)
                {
                    _GroupAppsMessage = value;
                    RaisePropertyChanged("GroupAppsMessage");
                }

            }
        }


        private Boolean _GroupMeetingLoading;
        public Boolean GroupMeetingLoading
        {
            get { return _GroupMeetingLoading; }
            set
            {
                if (_GroupMeetingLoading != value)
                {
                    _GroupMeetingLoading = value;
                    RaisePropertyChanged("GroupMeetingLoading");
                }

            }
        }

        private String _GroupMeetingMessage;
        public String GroupMeetingMessage
        {
            get { return _GroupMeetingMessage; }
            set
            {
                if (_GroupMeetingMessage != value)
                {
                    _GroupMeetingMessage = value;
                    RaisePropertyChanged("GroupMeetingMessage");
                }

            }
        }


        #endregion


        #region Commands
            public RelayCommand <SelectionChangedEventArgs> MeetingSelectionCommand { get; private set; }
            private void HandleMeetingSelectionCommand(SelectionChangedEventArgs args)
            {
                if (args.AddedItems.Count > 0)
                {
                    SendNavigationRequestMessage(new Uri(String.Format("/Views/pageMeeting.xaml?MeetingID={0}", SelectedMeeting.ID), UriKind.Relative));
                }
            }

            public RelayCommand<SelectionChangedEventArgs> GroupAppSelectionCommand { get; private set; }
            private void HandleGroupAppSelectionCommand(SelectionChangedEventArgs args)
            {
                if (args.AddedItems.Count > 0)
                {
                    MarketplaceDetailTask task = new MarketplaceDetailTask()
                    {
                        ContentIdentifier = SelectedApp.ApplicationID,
                        ContentType = MarketplaceContentType.Applications
                    };
                    task.Show();
                }
            }

            public RelayCommand<SelectionChangedEventArgs> MainMenuSelectionCommand { get; private set; }
            private void HandleMainMenuSelectionCommand(SelectionChangedEventArgs args)
            {
                if (args.AddedItems.Count > 0)
                {
                    string pageName = string.Empty;
                    Model.MenuItem item = args.AddedItems[0] as Model.MenuItem;

                    switch (item.Title)
                    {
                        case "about":
                            pageName = "pageAbout.xaml";
                            break;
                        case "news":
                            pageName = "pageNews.xaml";
                            break;
                        case "settings":
                            pageName = "pageSettings.xaml";
                            break;
                        case "group apps":
                            pageName = "pageGroupApps.xaml";
                            break;
                        case "links":
                            pageName="pageLinks.xaml";
                            break;
                        default:
                            break;
                    }



                    if (pageName != string.Empty)
                    {
                        SendNavigationRequestMessage(new Uri(String.Format("/Views/{0}", pageName), UriKind.Relative));
                    }



                }

            }

            public RelayCommand TwitterSearchCommand { get;  private set; }
            private void HandleTwitterSearchCommand()
            {
                LoadTweets();
            }

            public RelayCommand GroupAppsSearchCommand { get; private set; }
            private void HandleGroupAppsSearchCommand()
            {
                UpdateGroupApps();
                //Apps.Clear();

            }

            public RelayCommand ShowAllGroupAppsCommand { get; private set; }
            private void HandleShowAllGroupAppsCommand()
            {
                SendNavigationRequestMessage(new Uri("/Views/pageGroupApps.xaml", UriKind.Relative ));
            }

            public RelayCommand MeetingsSearchCommand { get; private set; }
            private void HandleMeetingsSearchCommand()
            {
                UpdateMeetings();
            }

        #endregion

        #region Messenger
            protected void SendNavigationRequestMessage(Uri uri)
            {
                Messenger.Default.Send<Uri>(uri, "NavigationRequest");
            }

        #endregion




            public void LoadTweets()
            {
               
                bool hasNetworkConnection = NetworkInterface.NetworkInterfaceType != NetworkInterfaceType.None;
                //string searchTerm = "#wpug OR #cdf_wpug";
                string searchTerm = "wpug";
                string twitter = "http://search.twitter.com/search.atom?rpp=10&q={0}";
                
                if (hasNetworkConnection == true)
                {
                    Tweets.Clear();
                    TwitterLoading = true;
                    TwitterMessage = String.Empty;

                    WebClient twitterFeed = new WebClient();
                    twitterFeed.DownloadStringCompleted += new DownloadStringCompletedEventHandler(twitterFeed_DownloadStringCompleted);
                    twitterFeed.DownloadStringAsync(new Uri(string.Format(twitter, searchTerm)));

                }
                else
                {
                    TwitterMessage= "There is currently no network coverage, try again later";
                    Tweets.Clear();
                }

                //Helpers.IsolatedStorageHelper.SaveFile("meetings.xml", xml);
                
            }

            void twitterFeed_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
            {
                TwitterLoading = false;

                if (e.Error == null)
                {
                    string xml = e.Result;
                    TwitterMessage = string.Empty;
                    var results = Helpers.TwitterHelper.ParseTweets(xml);
                    _Tweets.Clear();

                    if (results.Count > 0)
                    {
                        foreach (var item in results)
                        {
                            Tweets.Add(item);
                        }
                    }
                    else
                    {
                        TwitterMessage = "No tweets found";
                    }
                    
                }
                else
                {
                    TwitterMessage = "Opps! There was a problem while getting the tweets, please try again later";

                }
            }

            public void LoadMeetings()
            {
                if (Helpers.IsolatedStorageHelper.FileExists("Meetings.xml"))
                {
                    GroupMeetingLoading = true;
                    var results = Helpers.MeetingHelper.GetMeetingsFromIsolatedStorage();
                    UpcomingMeetings.Clear();
                    foreach (var item in results)
                    {
                        UpcomingMeetings.Add(item);
                    }
                    GroupMeetingLoading = false;
                }
                else
                {
                    //no file in isolated storage so download it
                    UpdateMeetings();
                }
            }

            public void UpdateMeetings()
            {
                WebClient meetingFeed = new WebClient();
                bool hasNetworkConnection = NetworkInterface.NetworkInterfaceType != NetworkInterfaceType.None;
                string xmldata = string.Format("http://bugail.com/cdfwpug/data/Meetings.xml?Ramdom={0}", Guid.NewGuid());
                UpcomingMeetings.Clear();
                GroupMeetingLoading = true;

                if (hasNetworkConnection == true)
                {
                    meetingFeed.DownloadStringCompleted += new DownloadStringCompletedEventHandler(meetingFeed_DownloadStringCompleted);
                    meetingFeed.DownloadStringAsync(new Uri(xmldata));
                }
                else
                {
                    GroupMeetingMessage = "There is currently no network coverage, try again later";
                }

                GroupMeetingLoading = false;
            }

            void meetingFeed_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
            {
                if (e.Error == null)
                {
                    string xml = e.Result;
                   
                    if (Helpers.IsolatedStorageHelper.FileExists("Meetings.xml"))
                    {
                        Helpers.IsolatedStorageHelper.DeleteFile("Meetings.xml");
                    }

                    Helpers.IsolatedStorageHelper.SaveFile("Meetings.xml", xml);
                    LoadMeetings();
                }
                else
                {
                    GroupMeetingMessage = "Opps! There was a problem while getting the meetings, please try again later";
                }

                GroupMeetingLoading = false;
            }

            public void LoadGroupApps()
            {
                if (Helpers.IsolatedStorageHelper.FileExists("UserApps.xml"))
                {
                    GroupAppsLoading = true;
                    var results = Helpers.AppHelper.GetAppsFromIsolatedStorage();
                    results = Helpers.AppHelper.SelectFeaturedApps(results.ToList(), 3);
                    Apps.Clear();
                    foreach (var item in results)
                    {
                        Apps.Add(item);
                    }
                    GroupAppsLoading = false;
                }
                else
                {
                    //no file in isolated storage so download it
                    UpdateGroupApps();
                }
            }

            public void UpdateGroupApps()
            {
                WebClient appsFeed = new WebClient();
                bool hasNetworkConnection = NetworkInterface.NetworkInterfaceType != NetworkInterfaceType.None;
                string xmldata = string.Format("http://bugail.com/cdfwpug/data/UserApps.xml?Random={0}", Guid.NewGuid());
                Apps.Clear();
                if (hasNetworkConnection == true)
                {
                    GroupAppsLoading = true;
                    appsFeed.DownloadStringCompleted += new DownloadStringCompletedEventHandler(appsFeed_DownloadStringCompleted);
                    appsFeed.DownloadStringAsync(new Uri(xmldata));
                }
                else
                {
                    GroupAppsMessage  = "There is currently no network coverage, try again later";
                    GroupAppsLoading = false;
                }

            }

            void appsFeed_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
            {
                if (e.Error == null)
                {
                    string xml = e.Result;
                    if (Helpers.IsolatedStorageHelper.FileExists("UserApps.xml"))
                    {
                        Helpers.IsolatedStorageHelper.DeleteFile("UserApps.xml");
                    }
                    Helpers.IsolatedStorageHelper.SaveFile("UserApps.xml", xml);
                    LoadGroupApps();
                }
                else
                {
                    GroupAppsMessage = "Opps! There was a problem while getting the apps, please try again later";

                }
                GroupAppsLoading = false;
            }

            public void LoadMainMenuItems()
            {
                MainMenuItems = Helpers.MenuItemHelper.GetMainMenuItems();
            }

            public override void Cleanup()
        {
            // Clean own resources if needed

            base.Cleanup();
        }




        
    }
}